package com.woniu34.upload.service;

import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Service
public class FileUploadService {


    //只接受这两种类型的图片
    private List<String> contentTypeList = Arrays.asList("image/jpeg","image/png");
    private String path = "D:/woniu/woniu34/woniu-ticket/filmimg";
    private String returnUrlPrefix="http://image.wncinema.com/img/";

    public String upload(MultipartFile file){
        //文件的原始名称
        String originalFilename = file.getOriginalFilename();
        String contentType = file.getContentType();
        if(contentTypeList.contains(contentType)){
            //把用户上传的文件名重新用随机数命名一下
            String fileName = System.currentTimeMillis()+"_"
                    +originalFilename.substring(originalFilename.lastIndexOf("."));

            //生成文件的全路径名
            String finalFileName = path+File.separator+fileName;


            try {
                //把用户上传的文件保存到指定位置
                file.transferTo(new File(finalFileName));
                return returnUrlPrefix+fileName;
            } catch (IOException e) {
                return null;
            }

        }

        return null;
    }
}
